'use strict';

const axios = require('axios')
const urlJoin = require('url-join')
// 比对版本号插件
const semver = require('semver')
module.exports = {
    getNpmInfo, 
    getNpmVersions,
    getNpmSemverVersion,
    getDefaultRegistry,
    getNpmLatestVersion
};

// 获取npm包信息
function getNpmInfo(npmName, registry) {
    // TODO
    if (!npmName) {
        return null
    }
    const registryUrl = registry || getDefaultRegistry()
    const npmInfoUrl = urlJoin(registryUrl, npmName)
    return axios.get(npmInfoUrl).then(response => {
        if (response.status === 200) {
            return response.data
        }
        return null
    }).catch(err => {
        return Promise.reject(err)
    })
}
// 默认registry
function getDefaultRegistry(isOriginal = false) {
    return isOriginal ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org'
}

// 获取npm包版本号
async function getNpmVersions(npmName, registry) {
    const data = await getNpmInfo(npmName, registry)
    if (data) {
        return Object.keys(data.versions)
    } else {
        return []
    }
}
// 获取高于此版本号的所有npm包版本号
function getNpmSemverVersions(baseVersion, versions) {
  
    versions = versions.filter((version) => {
    
        return semver.satisfies(version, `^${baseVersion}`)
    }).sort((a, b) => {
        return semver.gt(b, a)
    })
    return versions
}
// 返回最高版本号npm包
async function getNpmSemverVersion(baseVersion, npmName, registry) {
    const versions = await getNpmVersions(npmName, registry)
    const newVersions = getNpmSemverVersions(baseVersion, versions)
    if (newVersions && newVersions.length > 0) {
        return newVersions[0]
    }

    return newVersions
}

async function getNpmLatestVersion(npmName, registry) {
    const versions =  await getNpmVersions(npmName, registry)
    if (versions) {
        return versions.sort((a, b) => semver.gt(b, a))[0]
    }
    return null
}